import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpErrorResponse, HttpHandler, HttpRequest, HttpResponse } from "@angular/common/http";
import { Observable } from "rxjs/Observable";
import { of } from "rxjs/observable/of";
import { Router } from "@angular/router";
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
import { catchError } from 'rxjs/operators';
import { mergeMap } from 'rxjs/operators';
import { NotificationService } from "./shared/utils/notification.service";

@Injectable()
export class InterceptorService implements HttpInterceptor {
	constructor(private notificationService: NotificationService, private router: Router) { }
	intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
		return next.handle(req).pipe(mergeMap((event: any) => {
			if (event instanceof HttpResponse && event.status === 200) {
				return this.handleData(event);
			}
			// 若一切都正常，则后续操作
			return of(event);
		}),
			catchError((err: HttpErrorResponse) => this.handleData(err))
		);
	}
	private handleData(
		event: HttpResponse<any> | HttpErrorResponse,
	): Observable<any> {
		// 业务处理：一些通用操作
		switch (event.status) {
			case 200:
				if (event instanceof HttpResponse) {
					const body: any = event.body;
					if (body.code && body.code === 103) {
						this.notificationService.smallBox({
							content: "登录超时,请登录",
							timeout: 3000
						});
						common.clearCookie('isLogin');
						common.clearCookie('WEBSIDE_SID');
						localStorage.clear();
						this.router.navigate(['/auth']);
					}
					return of(event); // 或者依然保持完整的格式
				} else {
					if (event.url.indexOf('redirect.html') >= 0 && event.error) {
						common.clearCookie('isLogin');
						common.clearCookie('WEBSIDE_SID');
						localStorage.clear();
						this.router.navigate(['/auth']);
					}
				}
				break;
			case 400: // 数据传参异常
				//    	 	this.message('数据传参异常');
				break;
			case 401: // 未登录状态码
				this.notificationService.smallBox({
					content: "登录超时,请登录",
					timeout: 3000
				});
				common.clearCookie('isLogin');
				common.clearCookie('WEBSIDE_SID');
				localStorage.clear();
				this.router.navigate(['/auth']);
				break;
			case 403:
				this.notificationService.smallBox({
					content: "未登录,请重新登录!",
					timeout: 3000
				});
				common.clearCookie('isLogin');
				common.clearCookie('WEBSIDE_SID');
				localStorage.clear();
				this.router.navigate(['/auth']);
				break;
			case 404:
				layer.closeAll('loading');
				console.log('接口未找到404');
				break;
			case 500:
				layer.closeAll('loading');
				console.log('接口500');
				break;
			default:
				// this.notificationService.smallBox({
				// 	content: "系统异常,请重新登录!",
				// 	timeout: 3000
				// });
				// common.clearCookie('isLogin');
				// common.clearCookie('WEBSIDE_SID');
				// localStorage.clear();
				// this.router.navigate(['/auth']);
				break;
		}
		return of(event);
	}

}